import { EditorState, convertToRaw, ContentState } from 'draft-js';
import React, { useEffect, useState } from 'react'
import { Editor } from "react-draft-wysiwyg";
import "react-draft-wysiwyg/dist/react-draft-wysiwyg.css";
import draftToHtml from 'draftjs-to-html';
import { connect } from 'umi';
import editorStyle from './index.less'
import htmlToDraft from 'html-to-draftjs';
function NewsEditor(props: any) {
    const { dispatch, currentNewsData, myEditorType,id,myCurrentNews } = props
    const [editorState, setEditorState] = useState<EditorState>(EditorState.createEmpty());
    useEffect(() => {
        console.log(myCurrentNews);
        // if(editorState)
        if (myEditorType === 'add') {
            return;
        }
        if (myEditorType === 'update') {
            // console.log('我有执行了')
            const contentBlock = myCurrentNews && htmlToDraft(myCurrentNews?.content);
            if (contentBlock) {
                const contentState = ContentState.createFromBlockArray(contentBlock.contentBlocks);
                const newEditorState = EditorState.createWithContent(contentState);
                setEditorState(newEditorState);
                
            }
        }

    }, [myCurrentNews])
    const editorBlur = () => {
        dispatch({
            type: 'StandBox/saveEditorText',
            payload: {
                editorText: draftToHtml(convertToRaw(editorState.getCurrentContent()))
            }
        })
    }
    return (
        <div>
            <Editor
                editorState={editorState}
                toolbarClassName="toolbarClassName"
                wrapperClassName="wrapperClassName"
                editorClassName={editorStyle["editorClassName"]}
                onEditorStateChange={(editorValue) => { setEditorState(editorValue) }}
                onBlur={() => { editorBlur() }}
            />
        </div>
    )
}
const mapStateToProps = (state: any) => {
    return {
        editorText: state.StandBox.editorText,
        currentNewsData: state.StandBox.currentNewsData,
    }
}

export default connect(mapStateToProps)(NewsEditor)